package com.iot08.api.interceptor;

import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.constant.Constant;
import com.iot08.api.service.AccountService;
import com.iot08.api.utils.SpringContextUtil;
import com.iot08.common.constant.CacheEnum;
import com.iot08.common.entity.app.Account;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

/**
 * @version 1.0
 * @Description: token校验
 * @author: Rock
 * @time: 2021/1/19 17:27
 */
@Slf4j
public class TokenInterceptor extends BaseInterceptor {

    @Resource
    private RedisClusterService redisClusterService;
    @Resource
    private AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accesstoken = request.getParameter("accesstoken");
        if (StringUtil.isBlank(accesstoken) && request.getRequestURI().contains("message")) {
            return true;
        }
        if (StringUtils.isEmpty(accesstoken)) {
            accesstoken = request.getHeader("accesstoken");
        }
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip)) {
            ip = request.getRemoteAddr();
        }

        if( "local".equals(SpringContextUtil.getActiveProfile()) ){
            // 本地不进行 accesstoken校验
            return true;
        }

        if (StringUtil.isBlank(accesstoken) && request.getRequestURI().contains("message")) {
            return true;
        }

        if (StringUtil.isNotBlank(accesstoken)) {
            String openid = redisClusterService.get(CacheEnum.UA.getKey() + accesstoken);
            if (StringUtil.isBlank(openid)) {

                String openidParam = request.getParameter("openid");
                if (StringUtils.isEmpty(openidParam)) {
                    openidParam = request.getHeader("openid");
                }
                if (StringUtil.isBlank(openidParam)) {
                    Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                    openidParam = (String) pathVariables.get("openid");
                }
//                if (StringUtil.isNotBlank(openidParam)) {
//                    Account account = accountService.findById(openidParam);
//                    if (account != null && accesstoken.equals(account.getAccesstoken()) && account.getAccesstokenTime() != null
//                            && DateUtil.nowTimestampToDouble() - account.getAccesstokenTime() > 518400) {
//                        //设置缓存token
//                        redisClusterService.setex(CacheEnum.UA.getKey() + a`ccesstoken, CacheEnum.UA.getExpire(), openidParam);
//                        return true;
//                    }
//                }
                /*Enumeration enumeration = request.getHeaderNames();
				StringBuilder headerStr = new StringBuilder();
				while (enumeration.hasMoreElements()){
				    Object name = enumeration.nextElement();
				    if(name != null){
                        headerStr.append(" name = ").append(name).append(". value = ").append(request.getHeader(name.toString()));
                    }
                }*/
                log.info("返回无效token, method={}. openid={}, accesstoken={}, url={}. ip={}. openidParam={}",
                        request.getMethod(), openid, accesstoken, request.getRequestURI(), ip, openidParam);
                returnJson(response, ResponseMap.fail(ResponseEnum.STATUS401.getCode(), ResponseEnum.STATUS401.getMsg()));
                return false;
            }
            if (Constant.PWDCHANGE.equals(openid) || Constant.INVALID.equals(openid)) {
                returnJson(response, ResponseMap.fail(ResponseEnum.STATUS402.getCode(),ResponseEnum.STATUS402.getMsg()));
                return false;
            }
            return true;
        } else {
            log.info("无token请求！ url={}", request.getRequestURI());
            returnJson(response, ResponseMap.fail(ResponseEnum.STATUS400.getCode(), "API.request.accesstokenNotNull"));
            return false;
        }
    }


}
